import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {adSystemApiUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';

@Component({
  selector: 'app-program-list',
  templateUrl: 'program-list.component.html',
  styleUrls: ['program-list.component.scss'],
  providers: []
})
export class ProgramListComponent implements OnInit {

  searchData = '';
  appletList = [];

  type: string;
  message: string;
  isShow = false;
  totalItems: number;
  itemsPerPage = 12;
  currentPage = 1;
  constructor(private router: Router,
              private httpService: HttpService) { }

  ngOnInit() {
    this.getAppletList(this.searchData, 1);
  }

  // 获取小程序列表
  getAppletList(name: string, page: number) {
    const url = `${adSystemApiUrl}/v1/admin/applet/list?name=${name}&page=${page}&pageSize=${this.itemsPerPage}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.totalItems = res.data.total;
        this.currentPage = res.data.current_page;
        this.appletList = res.data.data;
      }
    );
  }

  // 重置
  reset() {
    this.searchData = '';
    this.getAppletList(this.searchData, 1);
  }
  // 搜索
  search() {
    this.getAppletList(this.searchData, 1);
  }

  pageChanged(event: any) {
    window.scrollTo(0, 0);
    this.getAppletList(this.searchData, event.page);
  }

  clearAllCache() {
    const url = `${adSystemApiUrl}/v1/admin/site_setting/cache_all_clear`;
    return this.httpService.httpPostAuth(url, {}).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '清除成功';
          this.isShow = true;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 跳转至清除缓存页
  turnClearCache(applet_uuid, name) {
    this.router.navigate(['admin/program-manage/clear-cache'], { queryParams: { 'applet_uuid': applet_uuid, 'name': name}});
  }
}
